﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.IO.Compression;

namespace WebUI.Controllers
{
    public class GZipAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (filterContext.Exception != null) return;

            var result = filterContext.Result;
            if (result is ViewResultBase)
            {
                HttpRequestBase request = filterContext.HttpContext.Request;
                HttpResponseBase response = filterContext.HttpContext.Response;

                string acceptEncoding = request.Headers["Accept-Encoding"];
                if (acceptEncoding == null) return;

                if (response.Filter == null) return;

                if (!response.ContentType.StartsWith("text/", StringComparison.CurrentCultureIgnoreCase)) return;

                if (acceptEncoding.ToLower().Contains("gzip"))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "gzip");
                }
                else if (acceptEncoding.ToLower().Contains("deflate"))
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "deflate");
                }
            }
        }

    }
}